from django.shortcuts import render, redirect, reverse
from django.http import JsonResponse
from django.views.generic import ListView
from utils.paginationbase import PaginationBase
from .models import ScheduleQueueconf, ScheduleCronConf, ScheduleCronConfLog

# 任务列表
class ConfListView(ListView, PaginationBase):
    model = ScheduleCronConf
    template_name = 'tasks_corn_conf_list.html'
    context_object_name = 'corn_confs'
    paginate_by = 10
    ordering = '-id'
    page_kwarg = 'p'

    def get_context_data(self, **kwargs):
        context = super(ConfListView, self).get_context_data(**kwargs)
        paginator = context.get('paginator')
        page_obj = context.get('page_obj')
        pagination_data = self.get_pagination_data(paginator, page_obj, 3, self.model)
        context.update(pagination_data)
        return context

# 任务对应日志列表
class ConfLogListView(ListView, PaginationBase):
    model = ScheduleCronConfLog
    template_name = 'tasks_corn_conf_log_list.html'
    context_object_name = 'cron_logs'
    paginate_by = 10
    ordering = 'id'
    page_kwarg = 'p'

    # queryset = ScheduleCronConfLog.objects.filter()

    # 只拿该任务的执行日志，所以重新get_queryset方法（get_queryset默认是拿模型所有数据）
    def get_queryset(self):
        # 获取url 中的值 比如http://127.0.0.1/admin/colortags/?name_text=红色
        task_id = self.request.GET.get('task_id')
        self.task_id = task_id

        return ScheduleCronConfLog.objects.filter(cron_id=task_id)

    def get_context_data(self, **kwargs):
        context = super(ConfLogListView, self).get_context_data(**kwargs)
        # context['username'] = 'zhiliao'
        paginator = context.get('paginator')
        page_obj = context.get('page_obj')
        pagination_data = self.get_pagination_data(paginator, page_obj, 3, self.model)
        context.update(pagination_data)
        return context


def to_task_cron_conf_add(request):
    return render(request, 'tasks_cron_conf_add.html')


def task_cron_conf_add(request):
    if request.method == 'POST':
        schedule_name = request.POST.get('schedule_name')
        task_path = request.POST.get('task_path')
        task_name = request.POST.get('task_name')
        task_desc = request.POST.get('task_desc')
        cron_conf = ScheduleCronConf(
            schedule_name=schedule_name,
            task_path=task_path,
            task_name=task_name,
            task_desc=task_desc
        )
        cron_conf.save()
        return JsonResponse({'code': 200, 'msg': 'success'})


def cron_conf_time_add(request):
    if request.method == 'GET':
        task_id = request.GET.get('task_id')
        print('============o==')
        print(task_id)
        cron_conf = ScheduleCronConf.objects.get(id=task_id)
        task_hour = cron_conf.task_hour
        task_minute = cron_conf.task_minute
        if task_hour is None:
            task_hour = ''
        if task_minute is None:
            task_minute = ''
        context = {
            'task_id': task_id,
            'task_hour': task_hour,
            'task_minute': task_minute
        }
        return render(request, 'tasks_cron_conf_time_add.html', context=context)
    if request.method == 'POST':
        task_id = request.POST.get('task_id')
        task_hour = request.POST.get('task_hour')
        task_minute = request.POST.get('task_minute')

        print(task_id)
        print(task_hour)
        print(task_minute)
        cron_conf = ScheduleCronConf.objects.get(id=task_id)
        cron_conf.task_hour = task_hour
        cron_conf.task_minute = task_minute
        cron_conf.save()

        return JsonResponse({'code': 200, 'msg': 'success'})


def cron_conf_params_add(request):
    if request.method == 'GET':
        task_id = request.GET.get('task_id')
        cron_conf = ScheduleCronConf.objects.get(id=task_id)
        task_args = cron_conf.task_args
        task_kwargs = cron_conf.task_kwargs
        queue = cron_conf.queue

        if queue:
            queue_id = queue.pk
        else:
            queue_id = None

        if task_args == None:
            task_args = ''
        if task_kwargs == None:
            task_kwargs = ''

        queue_confs = ScheduleQueueconf.objects.all()
        context = {
            'task_id': task_id,
            'task_args': task_args,
            'task_kwargs': task_kwargs,
            'queue_confs': queue_confs,
            'queue_id': queue_id
        }

        return render(request, 'tasks_cron_conf_params_add.html', context=context)

    if request.method == 'POST':
        task_id = request.POST.get('task_id')
        task_args = request.POST.get('task_args')
        task_kwargs = request.POST.get('task_kwargs')
        queue_conf_id = request.POST.get('queue_conf_id')

        cron_conf = ScheduleCronConf.objects.get(id=task_id)
        cron_conf.task_args = task_args
        cron_conf.task_kwargs = task_kwargs
        cron_conf.queue_id = queue_conf_id
        cron_conf.save()

        return JsonResponse({'code': 200, 'msg': 'success'})


def is_active_task(request):
    if request.method == 'POST':
        context = {
            'code': 200,
        }
        id = request.POST.get('id')
        is_active = request.POST.get('is_active')

        cron_conf = ScheduleCronConf.objects.get(id=id)
        if is_active == '1':
            cron_conf.is_active = 0
            cron_conf.save()
            context['msg'] = '停用成功'
        if is_active != '1':
            cron_conf.is_active = 1
            cron_conf.save()
            context['msg'] = '启用成功'

        return JsonResponse(context)


# 队列列表
class QueueListView(ListView, PaginationBase):
    model = ScheduleQueueconf
    template_name = 'tasks_queue_conf_list.html'
    context_object_name = 'scheduleQueueconfs'
    paginate_by = 10
    ordering = '-id'
    page_kwarg = 'p'

    def get_context_data(self, **kwargs):
        context = super(QueueListView, self).get_context_data(**kwargs)
        paginator = context.get('paginator')
        page_obj = context.get('page_obj')
        pagination_data = self.get_pagination_data(paginator, page_obj, 3, self.model)
        context.update(pagination_data)
        return context


# 队列添加页面
def to_task_queue_add(request):
    return render(request, 'tasks_queue_conf_add.html')


# 队列添加功能
def task_queue_add(request):
    if request.method == 'POST':
        queue_name = request.POST.get('queue_name')
        routing_key = request.POST.get('routing_key')

        queue = ScheduleQueueconf(queue_name=queue_name, routing_key=routing_key)
        queue.save()

        return JsonResponse({'code': 200, 'msg': 'success'})
